package com.shiroha.user.service.impl;

import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.shiroha.common.exception.AuthenticationException;
import com.shiroha.user.enums.ApplyStatus;
import com.shiroha.user.mapper.GroupApplicationMapper;
import com.shiroha.user.pojo.GroupApplication;
import com.shiroha.user.pojo.dto.GroupApplicationDTO;
import com.shiroha.user.service.IGroupApplicationService;
import com.shiroha.user.service.IGroupMemberService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

import static com.shiroha.user.pojo.table.Tables.GROUP_APPLICATION;

@Service
@AllArgsConstructor
@Slf4j
public class GroupApplicationServiceImpl extends ServiceImpl<GroupApplicationMapper, GroupApplication> implements IGroupApplicationService {

    private final IGroupMemberService groupMemberService;

    /**
     * 申请入群
     *
     * @param groupApplicationDTO DTO对象
     * @return 申请是否成功
     */
    @Override
    public boolean applyGroup(GroupApplicationDTO groupApplicationDTO) {
        GroupApplication groupApplication = new GroupApplication();
        groupApplication.setGroupId(groupApplicationDTO.getGroupId());
        groupApplication.setUserId(groupApplication.getUserId());
        groupApplication.setApplyReason(groupApplicationDTO.getApplyReason());
        return this.save(groupApplication);
    }

    /**
     * 获取群组的全部入群申请
     *
     * @param userId  访问者ID
     * @param groupId 群组ID
     * @return 入群申请列表
     */
    @Override
    public List<GroupApplication> getAllGroupApplication(UUID userId, Long groupId) {
        // 检验是否拥有管理员权限
        if(!groupMemberService.isAdminForGroup(userId, groupId)) {
            throw new AuthenticationException("没有该权限");
        }

        QueryWrapper queryWrapper = QueryWrapper.create()
                .where(GROUP_APPLICATION.GROUP_ID.eq(groupId));
        return this.list(queryWrapper);
    }

    /**
     * 处理入群申请
     * @param userId 访问者ID
     * @param groupId 群组ID
     * @param applicationId 申请ID
     * @param isApproved 是否同意申请
     * @return 处理是否成功
     */
    @Override
    public boolean handleApplication(UUID userId, Long groupId, Long applicationId, boolean isApproved) {
        // 检验是否拥有管理员权限
        if(!groupMemberService.isAdminForGroup(userId, groupId)) {
            throw new AuthenticationException("没有该权限");
        }

        ApplyStatus status = isApproved ? ApplyStatus.APPROVED : ApplyStatus.REJECTED;
        return this.updateChain()
                .set(GROUP_APPLICATION.STATUS, status)
                .where(GROUP_APPLICATION.ID.eq(applicationId))
                .update();
    }
}
